<template>
  <div id="questionAdd">
    <!--搭建布局-->
    <!--编写接口-->
    <!--交互-->

    <el-row>
      <el-col :span="24">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="question_ruleForm">
          <el-form-item label="试题题目" prop="title">
            <el-input v-model="ruleForm.title" placeholder="试题题目"></el-input>
          </el-form-item>

          <!-- 请求拦截  -->
          <!--:data="{file:'file'}"
            -->
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :before-upload="beforeUpload"
            :http-request="handleUpload"
          >
            <img v-if="ruleForm.img" :src="ruleForm.img" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即添加</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {uploadFile} from "../../api/upload";

  export default {
    name: "questionAdd",

    data() {
      return {
        ruleForm: {
          title: '',
          course: '',
          img: '',
          rightChoose: '',
          chooseTitle: '',//
          choose: []
        },
        /*效验规则*/
        rules: {
          title: [
            {required: true, message: '请输入题目', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      beforeUpload(file) {//file 回调自带
        // const isJPG = file.type === 'image/*';
        const isLt2M = file.size / 1024 / 1024 < 2;

        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是图片!');
        // }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        //isJPG &&
        return isLt2M;
      },
      submitForm(formName) {
        //校验
        this.$refs[formName].validate((valid) => {
          // valid: false : 校验失败
          if (valid) {
            //数据请求
            return true;
          }

          else {
            // 校验失败
            return false;

          }
        })
      },
      handleUpload(params) {
        let fileObj = params.file;
        // console.dir(this.$refs.file.files[0]);
        // 文件上传 需要结合ajax 才能文件上传
        let formData = new FormData();

        // 添加参数
        formData.append("filename", fileObj.size + '');//binary : 二进制
        formData.append("photos", fileObj);

        // 上传
        uploadFile(formData).then(res => {
          console.log(res);
          this.ruleForm.img = res.data.img;
        })
      }
    }
  }
</script>

<!--
scoped : 样式模块化  类的样式 id的样式 ac23434
如果想要修改elementUI的样式 需要把scoped取消
保险的做法 每个样式亲都加id

-->
<style>


  #questionAdd .avatar-uploader-icon {
    font-size: 32px;
    border: 1px dashed #8f9098;
    padding: 30px;


  }
</style>
